package com.zlkj.pro.modular.business.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.stylefeng.roses.kernel.rule.enums.YesOrNotEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlkj.pro.core.enums.MsgTemplateEnum;
import com.zlkj.pro.core.enums.ReportStatusEnum;
import com.zlkj.pro.modular.admin.entity.Config;
import com.zlkj.pro.modular.admin.service.ConfigService;
import com.zlkj.pro.modular.business.entity.AgentEntity;
import com.zlkj.pro.modular.business.entity.ReportEntity;
import com.zlkj.pro.modular.business.service.AgentService;
import com.zlkj.pro.modular.business.service.MessageService;
import com.zlkj.pro.modular.business.service.ReportService;
import com.zlkj.pro.modular.business.service.TaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author liyang
 * @date 2024/4/6
 * @time 14:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class TaskServiceImpl implements TaskService {

    @Autowired
    private ConfigService configService;

    @Autowired
    private ReportService reportService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private AgentService agentService;


    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); // 设置格式模式
    DateTimeFormatter localDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 设置格式模式


    @Override
    public String sendTodayNotice() {
        AtomicReference<String> result = new AtomicReference<>("");

        // 设置动态配置
        List<Config> configs = findConfig();
        // 报备有效期提前提醒天数
        int REPORT_END_REMIND = Integer.parseInt(configs.stream().filter(c -> c.getCode().equals("REPORT_END_REMIND")).findFirst().get().getValue());

        // 查询今天有效期临近的报备单
        LocalDate today = LocalDate.now(); // 获取今天的日期
        LocalDate dateAfterRemindDays = today.plusDays(REPORT_END_REMIND);  // 加上报备有效期提前提醒天数

        LambdaQueryWrapper<ReportEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReportEntity::getExpirationDateEnd, dateAfterRemindDays);
        queryWrapper.eq(ReportEntity::getDelFlag, "N");
        List<Integer> status = new ArrayList<>();
        //status.add(1);// 报备中
        status.add(2);// 客户商谈中
        queryWrapper.in(ReportEntity::getStatus, status);
        List<ReportEntity> list1 = reportService.list(queryWrapper);
        list1.forEach(report -> {
            result.set(result + "----" + report.getCode() + " " + report.getExpirationDateEnd() + "即将到期已提醒----");
            //AgentEntity agent = agentService.getById(report.getAgentId());
            messageService.sendMessage(MsgTemplateEnum.D,
                    report.getId(),
                    null,
                    Stream.of(report.getCustomerName(),report.getCode(), dateFormatter.format(report.getCreateTime()),
                                    localDateFormatter.format(report.getExpirationDateEnd()))
                            .collect(Collectors.toList()), //"报备客户", "报备编号", "报备日期", "报备有效期"
                    "报备有效期临近");
        });

        //更新发送提醒时间
        LocalDate date = LocalDate.now();
        list1.forEach(report -> {
            report.setSendMsgDate(date);
            reportService.updateById(report);
        });

        // 查询今天要失效的过期报备单
        LambdaQueryWrapper<ReportEntity> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(ReportEntity::getExpirationDateEnd, LocalDate.now());
        queryWrapper2.eq(ReportEntity::getDelFlag, "N");
        List<Integer> status2 = new ArrayList<>();
        status2.add(1);// 报备中
        status2.add(2);// 客户商谈中
        queryWrapper2.in(ReportEntity::getStatus, status2);
        List<ReportEntity> list2 = reportService.list(queryWrapper2);
        list2.forEach(report -> {
            result.set(result + "----" + report.getCode() + " " + report.getExpirationDateEnd() + "报备已过期----");
            AgentEntity agent = agentService.getById(report.getAgentId());
            messageService.sendMessage(MsgTemplateEnum.K,
                    report.getId(),
                    null,
                    Stream.of(agent.getName(),report.getCustomerName(),report.getCode(),
                                    localDateFormatter.format(report.getExpirationDateEnd()))
                            .collect(Collectors.toList()), //"代理商", "报备客户", "报备编号", "报备有效期"
                    "报备已过期");
            // 报备单失效
            report.setStatus(ReportStatusEnum.FAIL.getCode());
            report.setInvalidSource("报备已过期");
            report.setInvalidReason("报备已过期");

            // 2024.06.26 ad by lb 以下三个节点更新 商谈中变更到下一状态时间  成交确认(客户认可、客户不认可)/报备逾期/PC端的商谈中订单终止
            report.setDiscussEndDate(LocalDate.now());

            reportService.updateById(report);
        });

        // 查询今天要失效的审批超时报备单
        LambdaQueryWrapper<ReportEntity> queryWrapper3 = Wrappers.lambdaQuery();
        queryWrapper3.eq(ReportEntity::getApplyEndDate, LocalDate.now());
        queryWrapper3.eq(ReportEntity::getDelFlag, "N");
        queryWrapper3.eq(ReportEntity::getStatus, 1);// 报备中
        List<ReportEntity> list3 = reportService.list(queryWrapper3);
        list3.forEach(report -> {
            result.set(result + "----" + report.getCode() + " " + report.getExpirationDateEnd() + "报备审批超时终止----");
            AgentEntity agent = agentService.getById(report.getAgentId());
            messageService.sendMessage(MsgTemplateEnum.K,
                    report.getId(),
                    null,
                    Stream.of(agent.getName(),report.getCustomerName(),report.getCode(),
                                    localDateFormatter.format(report.getApplyEndDate()))
                            .collect(Collectors.toList()), //"代理商", "报备客户", "报备编号", "报备有效期"
                    "报备审批超时终止");
            // 报备单失效
            report.setStatus(ReportStatusEnum.FAIL.getCode());
            report.setInvalidSource("报备审批超时终止");
            report.setInvalidReason("报备审批超时终止");
            reportService.updateById(report);
        });

        return result.get();
    }

    @Override
    public void resetCerNumber() {
        LambdaQueryWrapper<AgentEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AgentEntity::getDelFlag, "N");
        List<AgentEntity> list = agentService.list(queryWrapper);
        list.forEach(agent -> {
            agent.setCerNumber(0);
        });
        agentService.updateBatchById(list);
    }

    public List<Config> findConfig() {
        LambdaQueryWrapper<Config> queryWrapper = new LambdaQueryWrapper<Config>();
        List<String> codes = new ArrayList<>();
        codes.add("REPORT_END_BUTTON");
        //codes.add("REPORT_DELAY_DAYS");
        codes.add("REPORT_END_REMIND");
        //codes.add("REPORT_TIME_SERIES");
        queryWrapper
                .in(Config::getCode, codes)
                .eq(Config::getDelFlag, YesOrNotEnum.N.getCode());
        return configService.list(queryWrapper);
    }

    public static void main(String[] args) {
        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 加上3天
        LocalDate dateAfterThreeDays = today.plusDays(3);
        // 格式化日期为年月日格式，例如：2023-04-05
        //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //String formattedDate = dateAfterThreeDays.format(formatter);
        // 输出结果
        System.out.println("今天的日期加上3天后的日期是: " + dateAfterThreeDays);
    }
}
